package halberd.io;

import java.awt.image.BufferedImage;

import halberd.DataType;
import halberd.ImgOut;
import halberd.data.ImgData;

public class BufferedImageOut implements ImgOut<BufferedImage> {
	public BufferedImage convert(ImgData imgData) {
		if (imgData == null) {
			return null;
		}
		DataType srcType = imgData.getDataType();
		if (srcType == null) {
			return null;
		}
		int[][][] ints = imgData.getDatas();
		if (ints == null) {
			return null;
		}
		int type = BufferedImage.TYPE_INT_RGB;
		if (imgData.getDataType() == DataType.RGBA) {
			type = BufferedImage.TYPE_INT_ARGB;
		}
		BufferedImage bufferedImage = new BufferedImage(imgData.getWidth(), imgData.getHeight(), type);
		if (srcType == DataType.GRAY || srcType == DataType.BINARY|| srcType == DataType.FOURIERED) {
			copyGray(ints, bufferedImage, imgData.getWidth(), imgData.getHeight());
		} else {
			copyRgb(ints, bufferedImage, imgData.getWidth(), imgData.getHeight());
		}
		return bufferedImage;
	}

	private void copyRgb(int[][][] src, BufferedImage dst, int w, int h) {
		for (int i = 0; i < w; ++i) {
			for (int j = 0; j < h; ++j) {
				int r = src[i][j][0];
				int g = src[i][j][1];
				int b = src[i][j][2];
				int rgb = (r * 256 + g) * 256 + b;
				if (rgb > 8388608) {
					rgb = rgb - 16777216;
				}
				dst.setRGB(i, j, rgb);
			}
		}
	}

	private void copyGray(int[][][] src, BufferedImage dst, int w, int h) {
		for (int i = 0; i < w; ++i) {
			for (int j = 0; j < h; ++j) {
				int g = src[i][j][4];
				int rgb = (g * 256 + g) * 256 + g;
				if (rgb > 8388608) {
					rgb = rgb - 16777216;
				}
				dst.setRGB(i, j, rgb);
			}
		}
	}
}
